package com.gitee.wsl.doc.soup.ext

import com.fleeksoft.ksoup.nodes.Element
import com.fleeksoft.ksoup.nodes.TextNode
import com.fleeksoft.ksoup.select.Elements


val Element.allElements get() = getAllElements()

internal fun Element.parseAttrAsInt(attr: String) = try {
    attr(attr).toInt()
} catch (e: NumberFormatException) {
    0
}

internal fun Elements.anyChildTagWithAttr(attribute: String): String? =
    firstOrNull { element -> element.attr(attribute).isNotBlank() }
        ?.attr(attribute)



fun Element.followingSibling(): Elements? {
    val rs = Elements()
    var tmp = nextSibling()
    while (tmp != null) {
        if (tmp is Element) {
            rs.add(tmp as Element)
        } else if (tmp is TextNode) {
            val txt = Element("text")
            txt.text((tmp).text())
            rs.add(txt)
        }
        tmp = tmp.nextSibling()
    }
    if (rs.size > 0) {
        return rs
    }
    return null
}

fun Element.precedingSibling(): Elements? {
    val rs = Elements()
    var tmp = previousSibling()
    while (tmp != null) {
        if (tmp is Element) {
            rs.add(tmp as Element)
        } else if (tmp is TextNode) {
            val txt = Element("text")
            txt.text((tmp as TextNode).text())
            rs.add(txt)
        }
        tmp = tmp.previousSibling()
    }

    if (rs.size > 0) {
        return rs
    }
    return null
}


fun Element?.setSameTagIndexInSiblings( index: Int) {
    if (this == null) {
        return
    }
    attr(EL_SAME_TAG_INDEX_KEY, index.toString())
}

fun Element.getJxSameTagIndexInSiblings(): Int {
    val `val` = attr(EL_SAME_TAG_INDEX_KEY)
    if (`val`.isBlank()) {
        return -1
    }
    return `val`.toInt()
}

fun Element?.setSameTagNumsInSiblings( nums: Int) {
    if (this == null) {
        return
    }
    attr(EL_SAME_TAG_ALL_NUM_KEY, nums.toString())
}

fun Element.getJxSameTagNumsInSiblings(): Int {
    val `val` = attr(EL_SAME_TAG_ALL_NUM_KEY)
    if (`val`.isBlank()) {
        return -1
    }
    return `val`.toInt()
}